package com.itheima.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;

/**
 * 开启端口、接收数据
 */
public class Server {

    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        //1.定义线程组
        //定义接收请求的线程组
        EventLoopGroup boss = new NioEventLoopGroup();
        //定义具体处理工作的线程组
        EventLoopGroup worker = new NioEventLoopGroup();
        //2.定义启动引导类
        ServerBootstrap bootstrap = new ServerBootstrap();
        //3.设置启动类的属性、绑定处理程序
        bootstrap.group(boss, worker)
                .channel(NioSctpServerChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //注册处理程序
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        //4.绑定端口
        try {
            ChannelFuture f = bootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        }
        finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
        //5.main方法中启动服务
    }

    public static void main(String[] args) throws InterruptedException {
        new Server(10010).run();
    }
}
